﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AssetsSys.BLL.AutoMapper;
using AssetsSys.DAL;
using AssetsSys.Dto;
using AssetsSys.Dto.Permission;
using AssetsSys.Dto.User;
using AssetsSys.model;
using Newtonsoft.Json;

namespace AssetsSys.BLL
{
    /// <summary>
    /// 用户
    /// </summary>
    public class UserManger
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="pwd"></param>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <param name="isForbid"></param>
        /// <returns></returns>
        public static bool Login(string phone, string pwd, out Guid userId, out string userName,out bool isForbid)
        {
            using (var logSvc = new UserService())
            {
                var log = logSvc.GetAll(m => m.PhoneNum == phone && m.PassWord == pwd).FirstOrDefaultAsync();
                if (log.Result == null)
                {
                    userId = Guid.Empty;
                    userName = "";
                    isForbid = false;
                    return false;
                }
                if (log.Result.Stop)
                {
                    userId = Guid.Empty;
                    userName = "";
                    isForbid = true;
                    return true;
                }
                userId = log.Result.Id;
                userName = log.Result.UserName;
                isForbid = false;
                return true;
            }
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task<PageModel> GetUserList(UserRequestDto request, Guid userId)
        {
            using (var logSvc = new UserService())
            {
                Expression<Func<User, bool>> predicate = (x => x.Id != userId
                                                               && (request.UserName == null || x.UserName.Contains(request.UserName))
                                                               && (request.PhoneNum == null || x.PhoneNum.Contains(request.PhoneNum))
                                                               && (request.DepartmentId == Guid.Empty || x.Department.Id == request.DepartmentId)
                );
                var totalCount = (await logSvc.GetAll(predicate, true).ToListAsync()).Count;
                var userlist = await logSvc.GetAll(predicate, true, request.PageIndex, request.PageSize).Select(x=>new UserModel()
                {
                    Id=x.Id,
                    UserName = x.UserName,
                    Email = x.Email,
                    PhoneNum = x.PhoneNum,
                    Stop = x.Stop,
                    DepartmentName = x.Department.DepartmentName
                }).ToListAsync();
                return (new PageModel()
                {
                    Count = totalCount,
                    Data = userlist.MapTo<List<UserModel>>()
                });
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static async Task<UserModel> GetUser(Guid id)
        {
            using (var logSvc = new UserService())
            {
                var user = (await logSvc.GetOne(id)).MapTo<UserModel>();
                return user ?? new UserModel();
            }
        }

        /// <summary>
        /// 获得用户权限菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<PermissionModel> GetPermissionByUserId(Guid id)
        {
            using (var useSvc = new UserService())
            {
                return await useSvc.GetAll(x=>x.Id==id).Select(m => new PermissionModel()
                {
                    PermissionName = m.Department.Permission.PermissionName,
                    PermissionMenu = m.Department.Permission.PermissionMenu
                }).FirstOrDefaultAsync();
            }
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="passWord"></param>
        /// <param name="email"></param>
        /// <param name="phone"></param>
        /// <param name="departmentId"></param>
        /// <returns></returns>
        public static async Task<bool> CreateUser(string username, string passWord, string email, string phone, Guid departmentId)
        {
            using (var creSvc = new UserService())
            {
                var user = await creSvc.GetAll(x => x.PhoneNum == phone, true).FirstOrDefaultAsync();
                if (user!=null)
                {
                    return false;
                }
                await creSvc.CreateAsync(new User()
                {
                    UserName = username,
                    PassWord = passWord,
                    Email = email,
                    PhoneNum = phone,
                    DepartmentId = departmentId
                });
                return true;
            }
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<bool> BanUser(Guid id)
        {
            using (var logSvc = new UserService())
            {
                var user = await logSvc.GetOne(id);
                user.Stop = !user.Stop;
                await logSvc.EditAsvnc(user);
                return true;
            }
        }

        /// <summary>
        /// 获取部门下所有列表
        /// </summary>
        /// <param name="departmentId"></param>
        /// <returns></returns>
        public static async Task<List<UserModel>> GetDepartmentUserList(Guid departmentId)
        {
            using (var useSvc = new UserService())
            {
                var l= await useSvc.GetAll(x=>x.DepartmentId== departmentId).Select(x => new UserModel()
                {
                    Id = x.Id,
                    UserName = x.UserName
                }).ToListAsync();
                return l;
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static async Task<UserModel> GetById(Guid userid)
        {
            using (var useSvc = new UserService())
            {
                return (await useSvc.GetOne(userid)).MapTo<UserModel>();
            }
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static async Task<bool> Update(UserModel model)
        {
            using (var useSvc = new UserService())
            {
                var oldModel = await useSvc.GetOne(model.Id);
                if (oldModel == null)
                {
                    return false;
                }
                oldModel.PhoneNum = model.PhoneNum ?? oldModel.PhoneNum;
                oldModel.UserName = model.UserName ?? oldModel.UserName;
                oldModel.Email = model.Email ?? oldModel.Email;
                oldModel.PassWord= model.PassWord ?? oldModel.PassWord;
                oldModel.DepartmentId = model.DepartmentId == Guid.Empty ? oldModel.DepartmentId : model.DepartmentId;
                await useSvc.EditAsvnc(oldModel);
            }
            return true;
        }
    }
}
